package com.mach.platform.api.config;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.mach.platform.api.domain.WxUser;
import com.mach.platform.service.CacheServiceImpl;
import com.mach.platform.api.service.LoginServiceImpl;
import com.mach.platform.utils.ReqStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

public class ApiInterceptor implements HandlerInterceptor {

    @Autowired
    private CacheServiceImpl cacheService;

    @Autowired
    private LoginServiceImpl loginService;

    /**
     * 自定义HandlerInterceptor接口的拦截方法，拦截微信的第三方请求API
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String requestUrl = request.getRequestURL().toString();
        if (requestUrl.contains("/getUserOpenIdInfo")) { // 如果是获取openId的请求，则放开限制
            return true;
        }
        String openId = request.getHeader("openId");

        if (null == openId) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            Map map = Maps.newHashMap();
            map.put("status", ReqStatus.LOGOUT.getValue());
            map.put("data", "");
            map.put("msg", "当前用户未获取有效的openId信息!");
            out.write(JSON.toJSON(map).toString());
            return false;
        }
        // 如果是手机验证码相关请求，验证用户是否已经获取到openId等信息
//        if (requestUrl.contains("/sendSms") || requestUrl.contains("/login")) {
//            /**
//             * 为了测试方便，先不验证session里面的openId信息，暂时先把这段代码注释掉，测试完成提交代码要把注释去掉
//             */
//            // 没有获取到openId信息或者openId错误
//            String sessionOpenId = (String) request.getSession().getAttribute(openId);
//            if (null == sessionOpenId) {
//                response.setContentType("application/json;charset=utf-8");
//                PrintWriter out = response.getWriter();
//                Map map = Maps.newHashMap();
//                map.put("status", ReqStatus.LOGOUT.getValue());
//                map.put("data", "");
//                map.put("msg", "当前用户未获取有效的openId信息! ");
//                out.write(JSON.toJSON(map).toString());
//                return false;
//            }
//            return true;
//        }
        // 检查微信小程序用户是否登录
        Object phone = cacheService.getCache(openId);
        if (null != phone) { // 先从缓存里面查询用户是否已经登录
            return true;
        }
        // 从数据库查询数据
        WxUser user = loginService.getWxUserByOpenId(openId);
        if (null != user) {
            return true;
        }
        // 没有登录
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        Map map = Maps.newHashMap();
        map.put("status", ReqStatus.LOGOUT.getValue());
        map.put("data", "");
        map.put("msg", "当前用户未登录! ");
        out.write(JSON.toJSON(map).toString());
        return false;
    }




}
